package com.hh.tc.ui.clockIn.monthDetails

import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.SavedStateHandle
import com.hh.base.log.Logger
import com.hh.base.ui.BaseViewModel
import com.hh.base.util.ext.DateType
import com.hh.base.util.ext.toDate
import com.hh.base.util.ext.toJsonString
import com.hh.base.util.ext.toShow
import com.hh.db.core.ObjectBoxUtil
import com.hh.db.core.ObjectBoxUtil.queryList
import com.hh.db.entity.ClockInRecord
import com.hh.db.entity.ClockInRecord_
import java.util.Date

/**
 * Create By hHui on 2025/4/8 10:06
 *
 * @description
 */
class MonthDetailViewModel(handle: SavedStateHandle) : BaseViewModel(handle) {
    val title = ObservableField("")
    val records = ObservableArrayList<ClockInRecord>()

    override fun initData() {
        initTitle()
        fillInData()
    }

    private fun initTitle() {
        getStringExtra("month")?.let {
            title.set(it)
        }
    }

    private fun fillInData() {
        //清除无效的数据
        ObjectBoxUtil.clockInRecordBox.queryList(
            ClockInRecord_.month.equal(title.get()).and(ClockInRecord_.begin.isNull).and(ClockInRecord_.end.isNull).and(ClockInRecord_.date.less(Date().toShow(DateType.DAY)))
        ).let {
            ObjectBoxUtil.clockInRecordBox.remove(it)
        }
        //只显示当天及之前的记录
        records.clear()
        ObjectBoxUtil.clockInRecordBox.queryList(
            ClockInRecord_.month.equal(title.get())
        ).let { list ->
            records.addAll(list.filter { it.date!! <= Date().toShow(DateType.DAY) })
        }
    }

    fun editBeginTime(record: ClockInRecord) {
        Logger.dft().v(TAG, "点击 ${record.toJsonString()}")
        showDateTimerPicker({ date, _ ->
            record.begin = date.toShow()
            ObjectBoxUtil.clockInRecordBox.put(record)
            fillInData()
        }, record.begin?.toDate())
    }

    fun editEndTime(record: ClockInRecord) {
        showDateTimerPicker({ date, _ ->
            record.end = date.toShow()
            ObjectBoxUtil.clockInRecordBox.put(record)
            fillInData()
        }, record.end?.toDate())
    }

}